package com.yexx.starter.ribbon.config;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;

import static com.yexx.core.constant.CommonConstants.LOG.*;

/**
 * Description: feign拦截器，只包含基础数据
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/12/07-18:11
 */
public class FeignInterceptorConfig {

    /**
     * 使用feign client访问别的微服务时，将上游传过来的xx、traceid等信息放入header传递给下一个服务
     */
    @Bean
    public RequestInterceptor baseFeignInterceptor() {
        return template -> {
            //传递traceId
            String traceId = MDC.get(LOG_TRACE_ID);
            if (StrUtil.isNotEmpty(traceId)) {
                template.header(TRACE_ID_HEADER, traceId);
            }
            //传递userId
            String userId = MDC.get(LOG_USER_ID);
            if (StrUtil.isNotEmpty(userId)) {
                template.header(USER_ID_HEADER, userId);
            }
        };
    }
}
